package com.wangmeng.book.server;

import org.apache.log4j.Logger;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * User: 王猛
 * Date: 13-9-24
 */
public class CommandListenerServer extends Thread {
    private static final Logger logger = Logger.getLogger(CommandListenerServer.class);
    private ServerSocket server;//服务器套接字
    private Integer port = 1818;//监听端口
    private AtomicBoolean isRun = new AtomicBoolean(false);

    @Override
    public void run() {
        logger.info("命令监听服务器开始启动...");
        super.run();
        try {
            server = new ServerSocket(port);
            isRun.set(true);
            logger.info("命令服务器异常成功,PORT:" + port);
            Socket client = null;
            while (isRun.get() && (client = server.accept()) != null) {
                logger.info("接收到客户端连接,IP:" + client.getInetAddress().getHostAddress());
                new CommandSession(client).start();
            }
        } catch (Exception ex) {
            logger.error("命令服务器运行异常", ex);
        } finally {
            logger.info("命令服务器退出");
        }
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public void toStopServer() {
        isRun.compareAndSet(true, false);
    }
}
